/**
 * @author Syang4
 * 
 * require jquery.js, jquery.json.min.js require require
 * 
 */

if (!QSAPI) {
	var QSAPI = {
		Widget : {}
	};
} else if (!QSAPI.Widget) {
	QSAPI.Widget = {};
}

QSAPI.Widget.TimeSales = function(container, option, callback, id) {
	var t = QS_Lang.timesales;
	this.containerId = null;
	this.container = null;
	this.id = null;
	this.profile = {
		hasSetting:false,
		width:500,
		height:300,
		fixHeight:true
	};
	this.el = null;
	this.dataList = null;
	this.tickerStr = '';
	// this.tickerKey = "";/*by jacye*/
	this.ticker = {};
	// this.isReplace=true;/*replace or add new*/
	this.maxRecord = 50;
	this.marketMap = {19:126,14:126,1:126};
	this.data = [];
	this.tsDataList;// data grid;
	this.startRangeEl = null;
	this.endRangeEl = null;
	this.startValEl = null;
	this.endValEl = null;
	this.sepRangeEl = null;
	this.btnEl = null;
	this.typeDDL = null;
	this.condDDL = null;
	this._isFiltering = false;
	this.$settingPanel = null;
	this.isShowHide = true;
	this.showHideCom = null;
	// this.orginHeight = 0;
	this.lastCallbackHeight = 0;
	this.intervalObj = null;
	this.intervalTime = 5 * 1000;
	this.hasSetting = true;
	this.hasFilter = true;
	this.fixHeight = true;
	this.firstRecord = null;
	this.lastRecord = null;
	this.loaded = false;
	this.headHeight = 32;
	this.conditionFuncs = {
        "<": function(a, b) { return a < b; },
        "<=": function(a, b) { return a <= b; },
        "=": function(a, b) { return Math.abs(a - b) <= 0.000001 },
        ">=": function(a, b) { return a >= b },
        ">": function(a, b) { return a > b },
        "R": function(v,a,b){return (a<=v&&v<=b)||(b<=v&&v<=a)}
    };
	
	this.pullPath = null;
	this.gExchangeMap =  null;
    //this.filterData=[{txt:'No Filter',val:'0'},{txt:'Filter',val:'1'}];

	this.id = id;
	this.profile = $.extend(this.profile, option);
	this.container = container;
	
	if (typeof (this.profile.filterBox) != "undefined" && typeof (this.profile.filterBox.buttonText) != "undefined") {
		t.tstxtgo = this.profile.filterBox.buttonText;
	}
	
	this.typeData=[{txt:t.tsftdef,val:'0'},{txt:t.tscolprice,val:'p'},{txt:t.tscolsize,val:'s'},{txt:t.tsftpr,val:'pr'},{txt:t.tsftsr,val:'sr'}];
    this.condData=[{txt:'>=',val:'>='},{txt:'>',val:'>'},{txt:'<=',val:'<='},{txt:'< ',val:'<'},{txt:'=',val:'='}];
    this.HTML = '<div class="rtq-tmsh"><div class="rtq-tmsh-hd"><div class="ddl ddlType"></div><div class="ddl ddlCond"></div><div class="range startRange"><input class="qs-ui-ipt" type="text" value="" /><div class="range-sp">-</div></div><div class="range endRange"><input class="qs-ui-ipt" type="text" value="" /></div><a class="qs-ui-btn go">'+t.tstxtgo+'</a></div><div class="data"></div></div>';
	this.callback = {};
	if (callback) {
		$.extend(this.callback, callback);
	}
};

QSAPI.Widget.TimeSales.prototype = {
	init : function() {
		/*this.id = Sid;
		this.profile = Profile;
		if (ContainerId) {
			this.containerId = ContainerId;
			this.container = $('#' + ContainerId);
		} else {
			this.container = this.profile.container || $(document.body);
		}*/
		if(this.profile.width){
			this.container.width(this.profile.width);
		}
		this.el = $(this.HTML);
		this.startRangeEl = this.el.find('.startRange');
		this.endRangeEl = this.el.find('.endRange');
		this.sepRangeEl = this.el.find('.range-sp');
		this.startValEl = this.startRangeEl.find('input');
		this.endValEl = this.endRangeEl.find('input');
		this.tmshHdEl = this.el.find('.rtq-tmsh-hd');
		this.btnEl = this.el.find('.go');
		this.title = this.el.find('.title');

		this.el.appendTo(this.container);
		this.w = 400;
		this.h = 400;
		if (this.hasSearch) {// add the autoComplete to title bar
			this.initAutoComplete();
		}
//		var self = this;

		if (this.profile.width) {
			this.w = this.profile.width;
		}
		if (typeof (this.profile.filterBox) != "undefined" && typeof (this.profile.filterBox.show) != "undefined") {
			this.isShowHide = this.profile.filterBox.show;
		}
		if (this.profile.intervalTime > 0) {
			this.intervalTime = this.profile.intervalTime;
		}
		if (typeof this.profile.hasSetting != 'undefined') {
			this.hasSetting = this.profile.hasSetting;
		}
		if (this.profile.height) {
			this.h = this.profile.height;
		}
		if (this.profile.maxRecord > 0) {
			this.maxRecord = this.profile.maxRecord;
		}
		if (this.profile.fixHeight === false) {
			this.fixHeight = false;
		}
		if (this.isShowHide) {
			// this.headHeight=this.tmshHdEl.outerHeight(true);
			this.h = this.h - this.headHeight
		}
		this._createDDL();
		this._bindEvent();
		this.tsDataList = new Util.DataGrid(this.el.find('div.data'), {}, {
			column : this.getColumns(),
			width : this.w,
			height : this.h,
			fixSize : false,
			htmlLayer : 'div',
			autoWidth : true,
			indexColKey : 'RID',
			sortable : false,
			autoHeight : !this.fixHeight
		}, {});
		if (this.hasSetting) {
			this._createSettingPannel();
		}
		this._showToolBar(this.isShowHide, this.hasSetting);
		if (this.profile.ticker) {
			this.addTicker(this.profile.ticker);
		}
		
		this.pullPath = QSAPI.getQSPullPath();
		this.gExchangeMap =  QSAPI.DataManager._getExchangeMap();
	},
	getColumns : function() {
		var t = QS_Lang.timesales;
		return [ {
			header : t.tscoltime,
			dataIndex : 'Time',
			width : '25%'
		}, {
			header : t.tscolexch,
			dataIndex : 'Exchange',
			width : '25%'
		}, {
			header : t.tscolprice,
			dataIndex : 'LastPrice',
			width : '25%',
			dataType : 'float',
			align : 'right'
		}, {
			header : t.tscolsize,
			dataIndex : 'Size',
			width : '25%',
			dataType : 'float',
			align : 'right'
		} ];
	},
	initUIConfig : function(config) {
		var dsettingPanel = config.settingPanel;
		if (dsettingPanel != null) {
			this.$settingPanel = $(dsettingPanel);
		}
	},
	_showToolBar : function(isShow, hasSetting) {
		if (isShow) {
			if (hasSetting) {
				this.showHideCom.btns["show"].select();
			}
			this.tmshHdEl[0].style.display = "";
		} else {
			this.tmshHdEl[0].style.display = "none";
		}
	},
	_createSettingPannel : function() {
		var self = this;
		var t = QS_Lang.timesales;
		this.$settingPanel.html('<div class="tab-show-or-hide-wrap"></div>');
		var showHide = this.$settingPanel.find('.tab-show-or-hide-wrap');
		this.showHideCom = new Util.ButtonGroup(showHide, [ {
			txt : t.tstxtshowtb,
			val : 'show'
		} ], {
			onClick : function(v, btn) {
				self.isShowHide = btn.isSelected;

				if (btn.isSelected) {
					self.tmshHdEl[0].style.display = "";
					self.changeOutSize(self.w, self
							._getDataGridHeight(self.h));
				} else {
					self.tmshHdEl[0].style.display = "none";
					self.changeOutSize(self.w, self
							._getDataGridHeight(self.h));
				}
			}
		}, {
			type : 'checkbox'
		});
	},
	_bindEvent : function() {
		var self = this;
		var t = QS_Lang.timesales;
		this.el.bind('click.ts', function(e) {
			if ($(e.target).hasClass('go')) {
				if (self.typeDDL.getValue() == '0') {
					return;
				} else {
					self._isFiltering = true;
					if (self._validNum().isEmpty) {
						Util.message(t.tstxtinn);
					} else if (!self._validNum().isValid) {
						Util.message(t.tstxtinvn);
					} else {
						self.startAutoUpdate();
						self.getLast50(self.ticker.gkey, false, false);
					}
				}
			}
		});
	},
	_validNum : function() {
		var isValid = true, isEmpty = false;
		var type = this.typeDDL.getValue();
		var reg1 = /^[0-9]+$/;
		if (type == 's') {
			var val = this.endValEl.val();// parseInt(this.endValEl.val(),10);
			if (val == '') {
				isEmpty = true;
			} else {
				if (!reg1.test(val)) {
					isValid = false;
				} else {
					this.endValEl.val(parseInt(val, 10));
				}
			}
		} else if (type == 'p') {
			if (this.endValEl.val() == '') {
				isEmpty = true;
			} else {
				var val = parseFloat(this.endValEl.val(), 10);
				if (val < 0 || isNaN(val)) {
					isValid = false;
				} else {
					this.endValEl.val(val);
				}
			}
		} else if (type == 'pr') {
			if (this.startValEl.val() == '') {
				isEmpty = true;
			} else {
				var val1 = parseFloat(this.startValEl.val(), 10);
				if (val1 < 0 || isNaN(val1)) {
					isValid = false;
				} else {
					this.startValEl.val(val1);
				}
			}
			if (this.endValEl.val() == '') {
				isEmpty = true;
			} else {
				var val2 = parseFloat(this.endValEl.val(), 10);
				if (val2 < 0 || isNaN(val2)) {
					isValid = false;
				} else {
					this.endValEl.val(val2);
				}
			}
		} else if (type == 'sr') {
			var val1 = this.startValEl.val();
			var val2 = this.endValEl.val();
			if (val1 == '') {
				isEmpty = true;
			} else {
				if (!reg1.test(val1)) {
					isValid = false;
				} else {
					this.startValEl.val(parseInt(val1, 10));
				}
			}
			if (val2 == '') {
				isEmpty = true;
			} else {
				if (!reg1.test(val2)) {
					isValid = false;
				} else {
					this.endValEl.val(parseInt(val2, 10));
				}
			}
		}
		return {
			isValid : isValid,
			isEmpty : isEmpty
		};
	},
	_createDDL : function() {
		var self = this;
		this.condDDL = new Util.DropDownList(this.el.find('.ddlCond'),
				function(t, v) {
				}, this.condData, {
					width : 65,
					actionInit : false
				});
		this.typeDDL = new Util.DropDownList(this.el.find('.ddlType'),
				function(t, v) {
					self._changeFilterUI(v);
				}, this.typeData, {
					width : 90,
					actionInit : false
				});
	},
	_disableFilterUI : function() {
		this.condDDL.setDisable(true);
		this.startValEl.val('').attr('disabled', true).addClass(
				'rtq-ddl-disable');
		this.endValEl.val('').attr('disabled', true)
				.addClass('rtq-ddl-disable');
		this.sepRangeEl.addClass('rtq-ddl-disable');
		this.btnEl.addClass('rtq-ddl-disable');
	},
	_enableFilterUI : function() {
		this.condDDL.setDisable(false);
		this.startValEl.attr('disabled', false).removeClass('rtq-ddl-disable');
		this.endValEl.attr('disabled', false).removeClass('rtq-ddl-disable');
		this.sepRangeEl.removeClass('rtq-ddl-disable');
		this.btnEl.removeClass('rtq-ddl-disable');
	},
	_changeFilterUI : function(v) {
		if (v == '0') {
			this._isFiltering = false;
			this._disableFilterUI();
			this.startAutoUpdate();
			this.getLast50(this.ticker.gkey, false, false);
		} else if (v == 'p' || v == 's') {
			this._enableFilterUI();
			this.startRangeEl.hide();
			this.sepRangeEl.hide();
			this.el.find('.ddlCond').show();
		} else {
			this._enableFilterUI();
			this.startRangeEl.show();
			this.sepRangeEl.show();
			this.el.find('.ddlCond').hide();
		}
	},
	_filterRow : function(price, size) {
		if (!this.hasFilter) {
			return true;
		}
		if (this._isFiltering == false) {
			return true;
		}
		var type = this.typeDDL.getValue();
		var cond;

		if (type == 'p') {
			cond = this.condDDL.getValue();
			return this.conditionFuncs[cond](parseFloat(price, 10), parseFloat(
					this.endValEl.val(), 10));
		} else if (type == 's') {
			cond = this.condDDL.getValue();
			return this.conditionFuncs[cond](parseInt(size, 10), parseFloat(
					this.endValEl.val(), 10));
		} else if (type == 'pr') {
			return this.conditionFuncs['R'](parseFloat(price, 10), parseFloat(
					this.startValEl.val(), 10), parseFloat(this.endValEl.val(),
					10));
		} else if (type == 'sr') {
			return this.conditionFuncs['R'](parseInt(size, 10), parseFloat(
					this.startValEl.val(), 10), parseFloat(this.endValEl.val(),
					10));
		}
	},

	_getType : function(exchCode, type) { // dealy or real-time
		var ty = 0;
		if (typeof (orderedStockExch) != "undefined" && type == 1) {
			if (exchCode == "126" && orderedStockExch["R"]
					&& orderedStockExch["R"].isOrderedUSCO) {
				ty = 1;
			} else if (exchCode != "126" && orderedStockExch["R"]
					&& orderedStockExch["R"][exchCode]) {
				ty = 1;
			}
		} else if (typeof (orderedIndexExch) != "undefined" && type == 10) {
			if (exchCode == "126" && orderedIndexExch["R"]
					&& orderedIndexExch["R"].isOrderedUSCO) {
				ty = 1;
			} else if (exchCode != "126" && orderedIndexExch["R"]
					&& orderedIndexExch["R"][exchCode]) {
				ty = 1;
			}
		}
		return ty;
	},
	_isExistColumn : function(dataIndex) {
		var cols = this.getColumns();
		for ( var i = 0, l = cols.length; i < l; i++) {
			if (cols[i].dataIndex == dataIndex) {
				return true;
			}
		}
		return false;
	},
	_calChg : function(gkey, lastprice) {
		var closePrice = typeof gData[gkey].ClosePrice != 'undefined' ? parseFloat(
				gData[gkey].ClosePrice, 10)
				: null;
		if (closePrice == null) {
			return '';
		} else {
			return (lastprice - closePrice).toFixed(2);
		}
	},
	_compareRecords : function(r1, r2) {
		if (this.firstRecord == null || this.lastRecord == null) {
			this.firstRecord = r1;
			this.lastRecord = r2;
			return false;
		}
		var flag = true;
		for ( var i in r1) {
			if (r1[i] != this.firstRecord[i]) {
				flag = false;
				break;
			}
		}
		for ( var i in r2) {
			if (r2[i] != this.lastRecord[i]) {
				flag = false;
				break;
			}
		}
		return flag;
	},
	getLast50 : function(gkey, needLoading, needCompare) {
		needLoading = needLoading === true ? true : false;
		needCompare = needCompare === false ? false : true;
		if (!gkey)
			return;
		var self = this;
		var ls = gkey.split(":");
		var type = gData[gkey].type;
		var tenforeExch = ls[0];
		if (type == 10) {
			tenforeExch = gData[gkey].tenforeCode;
		}
		var tkey = tenforeExch + ":" + gData[gkey].type + ":" + ls[1];

		if (needLoading && typeof self.showLoading == 'function') {
			self.showLoading(true);
		}
		// this.startAutoUpdate();
		this.getTimeSales(tkey, function(o) {
			//o = o.replace(/(^\s*)|(\s*$)/g, '');
			if (o == null || o == '' || o == []) {
				if (needLoading
						&& typeof self.hideLoading == 'function') {
					self.hideLoading();
				}
				return false;
			}
			//var o = $.evalJSON(o);
			var tickers = [];
			tsData = o.data || [];
			var exch, lastprice, rid, size, chg;
			if (tsData.length != 0) {
				var len = tsData.length > self.maxRecord ? self.maxRecord : tsData.length;
				var firstRecord = tsData[0], lastRecord = tsData[len - 1];
				if (needCompare && self._compareRecords(firstRecord, lastRecord)) {
					if (needLoading && typeof self.hideLoading == 'function') {
						self.hideLoading();
					}
					return;
				}

				self.data = [];
				self.tsDataList.empty();
				// var
				// len=tsData.length>self.maxRecord?self.maxRecord:tsData.length;
				var needExch = self._isExistColumn('Exchange');
				var needChg = self._isExistColumn('Chg');
				for ( var i = len - 1; i >= 0; i--) {
					if (needExch) {
						exch = typeof self.gExchangeMap[tsData[i].exch] == 'undefined' ? ''
								: self.gExchangeMap[tsData[i].exch];
					}
					if (needChg) {
						chg = self._calChg(gkey, parseFloat(
								tsData[i].price, 10));
					}
					// lastprice=NumFmt.Fmt(tsData[i].price,false,'',4);
					lastprice = parseFloat(tsData[i].price, 10)
							.toFixed(2);
					size = parseInt(tsData[i].size, 10);
					// rid=parseInt(Math.random()*1000000000000+1);
					if (self._filterRow(lastprice, size)) {// judge
															// price
															// or
															// size
						self.data.push({
							Time : self.formateDate(tsData[i].time),
							Exchange : exch,
							LastPrice : lastprice,
							Size : size,
							RID : i,
							Chg : chg
						});
					}
				}
				// if((self.data.length-self.maxRecord)>0){
				// self.data=self.data.slice(0,self.maxRecord);
				// }
				self.tsDataList.reBindData(self.data);
				self.changeOutSize(self.w, self.h);
			}
			if (needLoading && typeof self.hideLoading == 'function') {
				self.hideLoading();
			}
		});
	},
	
	formateDate:function(value,long) {
	    //value stand for second
	    //var dx = new Date().getTimezoneOffset() * 60000;
	    var t = startTick + parseInt(value) * 1000;
	    var dt = new Date(t);
	    return (dt == null) ? "--" :(long?QS_DateFmt.getLongTime(dt):QS_DateFmt.to12HrTime(dt));
	},
	_getDataGridHeight : function(h) {
		return this.isShowHide ? (h - this.headHeight) : (h + this.headHeight);
	},
	exportTimeSales : function(gkey) {
		if (!gkey)
			return;
		var ls = gkey.split(":");
		var pullKey = ls[0] + ":" + gData[gkey].type + ":" + ls[1];
		this.exportTimeSales(pullKey, null);
	},
	changeOutSize : function(w, h) {
		var parent = this.el.parent();
		w = w > 0 ? w : parent.width();
		h = h > 0 ? h : parent.height();
		var flag = false;
		if (w != this.w) {
			this.w = w;
			flag = true;
		}
		if (h != this.h) {
			this.h = h;
			flag = true;
		}
		if (this.fixHeight && flag) {
			this.tsDataList.resize(w, h);
		}
		this.onHeightChange(this.el.outerHeight(true));
	},
	onHeightChange : function(height) {
		if (!this.loaded) {
			this.loaded = true;
			this.lastCallbackHeight = height;
			if (typeof this.callback.onLoad == 'function') {
				this.callback.onLoad({
					component : 'timesales',
					height : this.lastCallbackHeight
				});
			}
		} else {
			if (this.lastCallbackHeight != height) {
				this.lastCallbackHeight = height;
				if (typeof this.callback.onHeightChange == 'function') {
					this.callback.onHeightChange({
						height : this.lastCallbackHeight,
						component : 'timesales'
					});
				}
			}
		}
	},
	addTicker : function(Ticker) { // 'XXX:IBM'
		if(typeof (Ticker) == 'undefined' || Ticker == null)
			return;
		var ticker = Ticker["exch"]+":"+Ticker["symbol"];
		if (this.tickerStr != ticker) {
			if (this.ticker) {
				// this.tValidation.unSubscribe([this.ticker.gkey]);
				this.stopAutoUpdate();
			}
			this.tickerStr = ticker;
		//	var self = this;
			//self.tValidation.checkTickers(self.tickerStr, function(o) {
			this.validateCallback([Ticker]);
			//}, false);
		}
	},
	validateCallback : function(gkeyList) {
		var d;
		if (typeof (this.hideLoading) == 'function'
				&& typeof (gkeyList) != 'undefined' && gkeyList.length == 0) {
			this.hideLoading();
		}
		var k = gkeyList.length;
		for ( var i = 0; i < k; i++) {
			var gkey = gkeyList[i].gkey;
			
			d = gData[gkey] ? gData[gkey] : gData[gIdMap[gkey]];
			if (this.ticker && this.ticker.gkey
					&& this.ticker.gkey == gkey) {
				continue;
			}
			if (this.ticker.gkey != '') {
				// this.tValidation.unSubscribe([this.ticker.gkey]); //
				// unsubscribe ticker
				for ( var o in this.ticker) {
					if (typeof this.ticker[o] == 'string') {
						this.ticker[o] = '';
					} else {
						this.ticker[o].empty();
					}
				}
			}
			this.ticker.gkey = gkey;
			if (this.setTitle) {
				this.setTitle('Time & Sales:', d.ticker);
			}
		}
		if (typeof this.callback.afterAcceptTicker == 'function') {
			this.callback.afterAcceptTicker(this.ticker.gkey);
		}
		this.startAutoUpdate();
		this.getLast50(this.ticker.gkey, true);
		// this.tickerStr = d.exch+":"+d.ticker;
		// this.data=[];
		// this.tsDataList.empty();
	},
	acceptTicker : function(Ticker) {// 'called from outside'
		if (typeof Ticker != 'undefined' && Ticker != '') {
			this.addTicker(Ticker);
			this.lastTicker = Ticker;
		}
	},
	startAutoUpdate : function() {
		var self = this;
		this.stopAutoUpdate();
		if (this.ticker.gkey && this.ticker.gkey != '') {
			this.intervalObj = setInterval(function() {
				self.getLast50(self.ticker.gkey);
			}, this.intervalTime);
		}
	},
	stopAutoUpdate : function() {
		if (this.intervalObj != null) {
			clearInterval(this.intervalObj);
			this.intervalObj = null;
		}
	},
	stopSubscribe : function() {
		this.stopAutoUpdate();
	},
	reSubscribe : function() {
		this.startAutoUpdate();
	},
	fileMenuCallback : function(val) {
		if (val == "export") { // export data to excel.
			this.exportTimeSales(this.ticker.gkey);
		}
	},
	autoCPCallback : function(o) {
		this.addTicker(o);
	},
	saveConfig : function() {
		return {
			ticker : this.tickerStr,
			title : this.getTitle(),
			isShowHide : this.isShowHide
		};
	},
	
	getTimeSales : function(pullKey, callback) {
//		var data = {
//			t : pullKey
//			cb
//		};
//		$.post(this.PULL_Path + "getTimeSales.jsp", data, callback);
		
		$.getJSON(this.pullPath + "getTimeSales.jsp?t="+pullKey+"&cb=?", function(o){
			var list=o;
			if(typeof o=='string'){
				list= eval("(" + o + ")");
			}
            if(typeof callback == "function"){
                callback(list);
            }
        });
	},
	exportTimeSales : function(pullKey, callback) {
		var url = this.pullPath + "exportTimeAndSaleData.jsp?t=" + pullKey;
		window.open(url);
	},
	
	clear : function() {
		this.el.unbind('.ts');
		// this.tValidation.unSubscribe([this.ticker.gkey]); // unsubscribe
		// ticker.
		this.stopAutoUpdate();
		for ( var p in this) {
			if (!p || p == 'clear') {
				continue;
			}
			this[p] = null;
			delete this[p];
		}
	}
};


